package fr.fbhelp.files
{
	import flash.events.Event;
	import flash.filesystem.File;
	
	import fr.fbhelp.config.UserLocale;
	import fr.fbhelp.events.ParserEvent;
	
	import mx.controls.Alert;
	import mx.core.FlexGlobals;
	import mx.events.CloseEvent;

	public class PathLocator
	{
		public var eclipseHelpIndexFolder:File;
		public var baseEclipseHelpFolder:File;
		public var baseHelpSourceFolder:File;
		public var nativeSeparator:String = File.separator;

		private var fbSetupFolder:File; 
		
		private static var ADOBE_FLASH_BUILDER_SETUP_FOLDER_NAME:String = "Adobe Flash Builder 4";
		
		public function PathLocator()
		{
		}

		public function initPathes():void
		{
			getFbSetupFolder();
		}
		
		private function gotFbSetupFolder():void
		{
			Output.append("Got Flash Builder Setup Folder: " + fbSetupFolder.nativePath);
			
			getEclipseFbPluginHelpFolder();
			getEclipseHelpIndexFolder();
			getChcHelpSourceFolder();
		}
		
		private function getFbSetupFolder():void
		{
			fbSetupFolder = File.applicationDirectory;
			
			var nativePath:String = fbSetupFolder.nativePath;
			fbSetupFolder = new File().resolvePath(nativePath);
			fbSetupFolder = fbSetupFolder.parent;
			fbSetupFolder = fbSetupFolder.resolvePath("Adobe" + nativeSeparator + ADOBE_FLASH_BUILDER_SETUP_FOLDER_NAME);
						
			if (fbSetupFolder != null && fbSetupFolder.exists)
			{
				gotFbSetupFolder();
			}
			else
			{
				browseForFbSetupFolder();
			}
		}
		
		private function browseForFbSetupFolder():void
		{
			Output.append("Failed to get Flash Builder Setup folder automatically. Browsing...");
			Alert.show("Failed to find the Flash Builder setup directory automatically, please locate it.",
				"Locate the Flash Builder setup directory.", Alert.OK, null, startBrowsingForFbSetupFolder, null, Alert.OK);
		}
		
		private function startBrowsingForFbSetupFolder(event:CloseEvent = null):void
		{
			try 
			{
				var folder:File = new File();
				Output.append("Trying to browse for Flash Builder setup directory");
				folder.addEventListener(Event.SELECT, onFbSetupFolderSelected, false, 0, true);
				folder.browseForDirectory("Select the Flash Builder setup directory");
			}
			catch (error:Error)
			{
				Output.append("Failed to browse for Flash Builder setup directory: ", error.message);
			}
		}
		
		private function onFbSetupFolderSelected(event:Event):void
		{
			fbSetupFolder = event.target as File;
			fbSetupFolder.removeEventListener(Event.SELECT, onFbSetupFolderSelected, false);
			
			if (fbSetupFolder.name == ADOBE_FLASH_BUILDER_SETUP_FOLDER_NAME)
			{
				gotFbSetupFolder();
			}
			else
			{
				Alert.show("The name of selected folder is '" + fbSetupFolder.name + "', not '" + 
					ADOBE_FLASH_BUILDER_SETUP_FOLDER_NAME + "'.\n" +
						"Are you sure the selected folder is correct?", 
						"Flash Builder setup folder name warning", (Alert.YES | Alert.NO), null, 
						onFbSetupFolderNameWarningClose, null, Alert.NO);
			}
		}
		
		private function onFbSetupFolderNameWarningClose(event:CloseEvent):void
		{
			if (event.detail == Alert.YES)
			{
				gotFbSetupFolder();
			}
			else
			{
				startBrowsingForFbSetupFolder();
			}
		}
		
		/**
		 * Detects Eclipse help folder which sould be something like this:  
		 * c:\Program Files\Adobe\Adobe Flash Builder 4\plugins\com.adobe.flexbuilder.help_4.0.0.272416 
		 */
		private function getEclipseFbPluginHelpFolder():void
		{
			baseEclipseHelpFolder = fbSetupFolder.resolvePath("plugins"+nativeSeparator+"com.adobe.flexbuilder.help_4.0.0.272416");
			
			if (baseEclipseHelpFolder.exists)
			{
				Output.append("Found base Eclipse Help folder: " + baseEclipseHelpFolder.nativePath);
			}
		}
		
		/**
		 * Detects Eclipse Help Index folder, the path is like this: 
		 * c:\Program Files\Adobe\Adobe Flash Builder 4\configuration\org.eclipse.help.base\index 
		 */
		private function getEclipseHelpIndexFolder():void
		{
			eclipseHelpIndexFolder = fbSetupFolder.resolvePath("configuration" + nativeSeparator + "org.eclipse.help.base" + nativeSeparator + "index");
			
			if (eclipseHelpIndexFolder.exists)
			{
				Output.append("Found Eclipse Help Index folder: " + eclipseHelpIndexFolder.nativePath);
			}
		}
		
		private function getChcHelpSourceFolder():void
		{
			var listing:Array = getAppStorageFolder().getDirectoryListing();
			for each (var f:File in listing)
			{
				if (f.name.indexOf("chc.") == 0)
				{
					baseHelpSourceFolder = f.resolvePath("Local Store");
				}
			}
			
			if (baseHelpSourceFolder != null && baseHelpSourceFolder.exists)
			{
				//Output.append("Found help folder: " + baseHelpFolder.nativePath);
				searchForHelpConfigs(baseHelpSourceFolder);
				return;
			}
			browseForHelpSourceFolder();
		}

		private function browseForHelpSourceFolder():void
		{
			Output.append("Failed to find the CHC help folder. Make sure you have launched Flash Builder Help at least one time before and have some local help content downloaded through it.");
			var folder:File = getAppStorageFolder();
			try
			{
				Output.append("Try browse for help folder. Base path: " + folder.nativePath);
				folder.addEventListener(Event.SELECT, onHelpSourceFolderSelected, false, 0, true);
				folder.browseForDirectory("Select the Help Directory, name must be 'Local Store'");
			}
			catch (error:Error)
			{
				Output.append("Failed to browse for dir, error: ", error.message);
			}
		}
		
		private function onHelpSourceFolderSelected(event:Event):void
		{
			Output.append("Help source folder selected: " + (event.target as File).nativePath);
			
			baseHelpSourceFolder = event.target as File;
			
			if (baseHelpSourceFolder != null && baseHelpSourceFolder.name == "Local Store" && baseHelpSourceFolder.exists)
			{
				//Output.append("Found help folder: " + baseHelpFolder.nativePath);
				searchForHelpConfigs(baseHelpSourceFolder);
			}
		}
		
		private function getAppStorageFolder():File
		{
			var appStoreFolder:File = File.applicationStorageDirectory;
			var nativePath:String = appStoreFolder.nativePath;
			var appStorageFolder: File = new File().resolvePath(nativePath);
			appStorageFolder = appStorageFolder.parent.parent;
			return appStorageFolder;
		}

		private function searchForHelpConfigs(baseHelpFolder:File):void
		{
			var s:String = File.separator;
			var helpCfgFolder:File = baseHelpFolder.resolvePath("HelpCfg");
			
			helpCfgFolder = helpCfgFolder.resolvePath(UserLocale.currentLocale);
			Output.append("Found help config locale folder: " + helpCfgFolder.nativePath);
			
			var pathesLocatedEvent:ParserEvent = new ParserEvent(ParserEvent.HELP_PATHES_LOCATED, true);
			pathesLocatedEvent.data = helpCfgFolder;
			FlexGlobals.topLevelApplication.dispatchEvent(pathesLocatedEvent);
		}
	}
}